package network.UDPStuAndTeacher;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceive implements Runnable{

    DatagramSocket socket = null;
    private int port;
    private String receiver;

    public TalkReceive(int port,String receiver) {
        this.receiver =receiver;
        this.port = port;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        while(true){

            //接受包
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);

            try {
                socket.receive(packet);


                //断开连接  bye
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);
                System.out.println(receiver+receiveData);

                //发送bye时，跳出循环，即断开连接
                if(receiveData.equals("bye")){
                    break;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        socket.close();
    }
}
